package com.wujunshen.prometheus;

import java.util.Objects;
import java.util.Properties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;

/**
 * @author frank woo(吴峻申) <br>
 * email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2020/2/7 5:33 下午 <br>
 */
public class PrometheusSpringApplicationRunListener implements SpringApplicationRunListener {
    private static final String SERVER_PORT_KEY = "management.server.port";
    private static final int SERVER_PORT_VALUE = 8081;
    
    private static final String ENDPOINTS_WEB_EXPOSURE_KEY =
            "management.endpoints.web.exposure.include";
    private static final String ENDPOINTS_WEB_EXPOSURE_VALUE = "*";
    
    private static final String METRICS_TAGS_APPLICATION_KEY = "management.metrics.tags.application";
    
    public PrometheusSpringApplicationRunListener(SpringApplication application, String[] args) {
    }
    
    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
    }
    
    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
    }
    
    @Override
    public void environmentPrepared(ConfigurableEnvironment env) {
        Properties props = new Properties();
        props.put(SERVER_PORT_KEY, SERVER_PORT_VALUE);
        props.put(ENDPOINTS_WEB_EXPOSURE_KEY, ENDPOINTS_WEB_EXPOSURE_VALUE);
        props.put(
                METRICS_TAGS_APPLICATION_KEY,
                Objects.requireNonNull(env.getProperty("spring.application.name")));
        env.getPropertySources().addLast(new PropertiesPropertySource("application", props));
    }
    
    @Override
    public void starting() {
    }
}
